
<template>
  <div class="section user-section">
    <div class="head">
      <van-nav-bar class="nav-bar">
        <template #left>
          <van-icon name="arrow-left" @click="router.go(-1)" />
        </template>

        <template #title>
          <div class="title">编辑报告</div>
        </template>
      </van-nav-bar>
    </div>
    <van-form @submit="onSubmit">
      <div style="display: flex" v-if="fromWhere != 'check'">
        <van-cell title="文档操作" label="上传还是暂存到本地" size="large" />
        <div
          style="
            background-color: white;
            display: flex;
            flex-direction: row;
            align-items: center;
          "
        >
          <van-button
            round
            type="success"
            size="small"
            style="width: 1.5rem; margin: 3px"
            native-type="submit"
            >上传</van-button
          >
          <van-button
            round
            type="warning"
            size="small"
            style="width: 1.5rem; margin: 3px"
            @click="store2local"
            >暂存</van-button
          >
        </div>
      </div>
      <div style="display: flex" v-else>
        <van-cell title="改报告" label="修改报告，说明问题" size="large" />
        <div
          style="
            background-color: white;
            display: flex;
            flex-direction: row;
            align-items: center;
          "
        >
          <van-button
            round
            type="success"
            size="small"
            style="width: 2rem; margin: 3px"
            native-type="submit"
            >确认修改</van-button
          >
        </div>
      </div>
      <van-cell-group style="margin-top: 5px">
        <van-field
          v-model="formState.reportTime"
          is-link
          readonly
          name="reportTime"
          label="报告时间"
          placeholder="点击选择时间"
          @click="showTime = true"
          :rules="rules.time"
        />
        <van-popup
          v-if="fromWhere != 'check'"
          v-model:show="showTime"
          position="bottom"
        >
          <van-datetime-picker
            type="date"
            v-model="currentDate"
            @confirm="onConfirmTime"
            @cancel="showTime = false"
          />
        </van-popup>
        <van-field
          v-model="formState.reportType"
          is-link
          readonly
          name="reportType"
          label="报告类型"
          placeholder="点击选择报告类型"
          @click="showType = true"
          :rules="rules.type"
        />
        <van-popup
          v-model:show="showType"
          v-if="fromWhere != 'check'"
          position="bottom"
        >
          <van-picker
            :columns="reportType"
            @confirm="onConfirmType"
            @cancel="showType = false"
          />
        </van-popup>
        <van-field
          name="devPeo"
          label="选择批改人"
          :rules="rules.devPeo"
          v-if="fromWhere != 'check'"
        >
          <template #input>
            <van-radio-group v-model="formState.devPeo" direction="horizontal">
              <van-radio :name="formState.devPeo1">{{
                formState.devPeo1
              }}</van-radio>
              <van-radio :name="formState.devPeo2">{{
                formState.devPeo2
              }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          name="isDone"
          label="是否可以抄写"
          :rules="rules.isDone"
          v-if="fromWhere === 'check'"
        >
          <template #input>
            <van-radio-group v-model="formState.isDone" direction="horizontal">
              <van-radio :name="`yes`">可以抄写</van-radio>
              <van-radio :name="`no`">不可以抄写</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="formState.comment"
          v-show="showComment"
          :readonly="fromWhere != 'check'"
          name="comment"
          type="textarea"
          autosize
          label="评价"
          placeholder="说明报告存在的问题"
          :rules="rules.comment"
        />
      </van-cell-group>
      <div style="display: flex; margin-top: 5px">
        <van-cell
          title="编辑正文"
          :label="'当前字数：' + textNum + '，目标字数：' + min_textNum"
          size="large"
        />
        <div
          style="
            background-color: white;
            display: flex;
            flex-direction: row;
            align-items: center;
          "
        >
          <van-button
            v-if="readOnly"
            round
            type="success"
            size="small"
            style="width: 2rem; margin: 3px"
            @click="Edit"
            >{{ fromWhere != "check" ? "开始编辑" : "开始批注" }}</van-button
          >
          <van-button
            v-else
            round
            type="danger"
            size="small"
            style="width: 2rem; margin: 3px"
            @click="Edit"
            >{{ fromWhere != "check" ? "完成编辑" : "批注完成" }}</van-button
          >
          <template
            v-if="
              fromWhere != 'check' &&
              (user.userInfo.userType === '积极分子' ||
                user.userInfo.userType === '预备党员')
            "
          >
            <van-button
              v-if="!showComment"
              round
              type="warning"
              size="small"
              style="width: 2rem; margin: 3px"
              @click="ShowComment"
              >查看批改</van-button
            >
            <van-button
              v-else
              round
              type="warning"
              size="small"
              style="width: 2rem; margin: 3px"
              @click="HideComment"
              >查看本人</van-button
            >
          </template>
        </div>
      </div>
      <div style="border: 1px solid #ccc; margin-top: 5px">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          mode="default"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          mode="default"
          @onCreated="handleCreated"
          @onChange="handleChange"
        />
      </div>
    </van-form>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  watch,
  onBeforeUnmount,
  shallowRef,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import toasts from "/@/views/components/toasts";
import { useStore } from "vuex";
import { submitReport, getReportContent, submitCheck } from "/@/api/report";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { report } from "process";

const router = useRouter();
const route = useRoute();
const showTime = ref(false);
const showType = ref(false);
const store = useStore();
const currentDate = ref(new Date());
const user = store.state.storage.user;
const fromWhere = ref();
const needComment = () => {
  if (fromWhere.value == "write") {
    if (formState.isSubmit === false) return false;
  }
};
const formState = reactive({
  reportTime: "",
  reportType: "",
  html: "",
  correctHtml: "",
  comment: "",
  isDone: false,
  isSubmit: false,
  isCorrect: false,
  devPeo1: "",
  devPeo2: "",
  devPeo: "",
  reportId: "-1", // 默认值-1如果有则改
  isDone: "no",
});

const reportType = [
  "入党申请书",
  "思想汇报",
  "初党总结",
  "高党总结",
  "个人自传",
  "入党志愿书",
  "转正申请书",
];
const min_textNum = ref(1500);

const onConfirmType = (value) => {
  formState.reportType = value;
  showType.value = false;
  calcMinTextNum();
};

const onConfirmTime = (value) => {
  formState.reportTime = value.format("yyyy-MM-dd");
  showTime.value = false;
};

function store2local() {
  var report = {};
  report.reportTime = formState.reportTime;
  report.reportType = formState.reportType;
  formState.html = valueHtml.value;
  report.html = valueHtml.value;
  report.devPeo = formState.devPeo;
  store.commit("storage/setReport", report);
  toasts.success("成功暂存本地");
}

//表单操作
const trigger = "onBlur";
const onSubmit = (value) => {
  if (fromWhere.value != "check") {
    // 不是从批改报告进来的
    if (showComment.value === true) {
      toasts.fail("只能上传自己的报告哦");
      return;
    } else if (readOnly.value === false) {
      toasts.fail("请确认完成编辑");
      return;
    }
    console.log("提交事件", value);
    calcMinTextNum();
    if (textNum.value < min_textNum.value) {
      toasts.fail(
        formState.reportType +
          "至少需要" +
          min_textNum.value +
          "字，可以先暂存本地"
      );
      return;
    } else {
      submitReport(
        {
          token: store.state.storage.user.token,
          reportTime: value.reportTime,
          reportType: value.reportType,
          html: valueHtml.value,
          devPeo: value.devPeo,
          reportId: formState.reportId,
        },
        (res) => {
          if (res.code === 0) {
            toasts.success("成功提交报告");
          }
        }
      );
    }
  } else {
    if (readOnly.value === false) {
      toasts.fail("请确认完成编辑");
      return;
    }
    console.log("提交修改", value);
    submitCheck(
      {
        token: store.state.storage.user.token,
        isDone: value.isDone,
        comment: formState.comment,
        correctHtml: valueHtml.value,
        reportId: formState.reportId,
      },
      (res) => {
        if (res.code === 0) {
          toasts.success("成功提交报告");
        }
      }
    );
  }
};

const checkTime = (value, rule) => {
  if (fromWhere.value === "check") return true; // 批报告不需要提交日期
  if (!value) return "请选择报告时间";
  return true;
};
const checkType = (value, rule) => {
  if (fromWhere.value === "check") return true; // 批报告不需要提交培养人
  if (!value) return "请选择报告类型";
  return true;
};
const checkDevPeo = (value, rule) => {
  if (fromWhere.value === "check") return true; // 批报告不需要提交培养人
  if (
    user.userInfo.userType != "积极分子" &&
    user.userInfo.userType != "预备党员"
  )
    return true;
  if (!value) return "请选择报告一个培养对象";
  return true;
};
const checkComment = (value, rule) => {
  if (showComment.value === false) return true;
  if (fromWhere.value === "check" && !value) return "请输入修改意见";
  return true;
};
const isDone = (value, rule) => {
  if (fromWhere.value === "check" && !value) return false; // 如果是来自修改报告，则需要提交
  return true;
};

const rules = {
  time: [{ validator: checkTime, trigger }],
  type: [{ validator: checkType, trigger }],
  devPeo: [{ validator: checkDevPeo, trigger }],
  comment: [{ validator: checkComment, trigger }],
  isDone: [{ validator: isDone, trigger }],
};

// 富文本操作
// 编辑器实例
var html = "";
const textNum = ref(0);
const readOnly = ref(true);
const showComment = ref(false);
const Edit = () => {
  readOnly.value = !readOnly.value;
  if (readOnly.value) {
    editorRef.value.disable();
  } else {
    editorRef.value.enable();
  }
};
const editorRef = shallowRef();
const valueHtml = ref("");
// 异步加载数据
onMounted(() => {
  formState.devPeo1 = user.userInfo.devPeo1;
  formState.devPeo2 = user.userInfo.devPeo2;
  fromWhere.value = route.params.fromWhere ? route.params.fromWhere : "";
  if (fromWhere.value === "" || fromWhere.value === "newRp") {
    // 新建的话先去读取本地存储
    showComment.value = false;
    var report = window.localStorage.getItem("REPORT_INFO");
    if (report != "null" && report != "") {
      // 从本地读取
      report = store.state.storage.report;
      formState.reportTime = report.reportTime;
      formState.reportType = report.reportType;
      formState.devPeo = report.devPeo;
      formState.html = report.html;
      toasts.success("成功读取本地报告");
      calcMinTextNum();
      setTimeout(() => {
        valueHtml.value = formState.html;
      }, 50);
    }
  } else if (fromWhere.value === "oldRp") {
    //从以前的报告来的
    getReportContent(
      {
        token: store.state.storage.user.token,
        reportId: route.params.reportId,
      },
      (res) => {
        console.log(res);
        if (res.code === 0) {
          console.log("编辑旧报告,", res);
          let report = res.content;
          formState.reportTime = report.reportTime;
          formState.reportType = report.reportType;
          formState.devPeo = report.devPeo;
          formState.html = report.html;
          formState.reportId = route.params.reportId;
          formState.correctHtml = report.correctHtml;
          formState.comment = report.comment;
          toasts.success("成功加载");
          calcMinTextNum();
          setTimeout(() => {
            valueHtml.value = formState.html;
          }, 50);
        }
      }
    );
  } else if (fromWhere.value === "check") {
    showComment.value = true;
    getReportContent(
      {
        token: store.state.storage.user.token,
        reportId: route.params.reportId,
      },
      (res) => {
        console.log(res);
        if (res.code === 0) {
          console.log("批改报告,", res);
          let report = res.content;
          formState.reportTime = report.reportTime;
          formState.reportType = report.reportType;
          formState.devPeo = report.devPeo;
          formState.html = report.html;
          formState.reportId = route.params.reportId;
          formState.correctHtml = report.correctHtml;
          formState.comment = report.comment;
          toasts.success("成功加载");
          calcMinTextNum();
          setTimeout(() => {
            valueHtml.value = formState.html;
          }, 50);
        }
      }
    );
  }
  setTimeout(() => {
    editorRef.value.disable();
  }, 100);
});

const ShowComment = () => {
  showComment.value = true;
  html = valueHtml.value; // 先将本人编辑的保存
  valueHtml.value = formState.correctHtml;
};
const HideComment = () => {
  showComment.value = false;
  formState.html = html; //读取本人保存的
  valueHtml.value = formState.html;
};
const toolbarConfig = {};
const editorConfig = { placeholder: "请在这里编辑报告..." };

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor) => {
  textNum.value = editor.getText().length;
};
function calcMinTextNum() {
  if (formState.reportType === "思想汇报") {
    //思想汇报最少字数 1500
    min_textNum.value = 1500;
  } else if (formState.reportType === "入党申请书") {
    //入党申请书最少字数2000
    min_textNum.value = 2000;
  } else if (formState.reportType === "个人自传") {
    //个人自传 6000
    min_textNum.value = 6000;
  } else if (formState.reportType === "入党志愿书") {
    //入党志愿书 900
    min_textNum.value = 900;
  } else if (formState.reportType === "转正申请书") {
    //转正申请书 2000
    min_textNum.value = 2000;
  } else if (formState.reportType === "初党总结") {
    // 初党总结 1500
    min_textNum.value = 1500;
  } else if (formState.reportType === "高党总结") {
    //高党总结2000
    min_textNum.value = 2000;
  }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>


<style lang="scss" scoped>
.user-section {
  background: var(--yu-gray-color--light);
  min-height: 100vh;

  .head {
    height: 50px;
    position: relative;
    .nav-bar {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      background: var(--yu-linear-bg-color);
      border: none;
      .van-icon {
        color: var(--yu-white-color);
      }
      .title {
        color: var(--yu-white-color);
      }
      &:after {
        border: none;
      }
    }
    .head-bg {
      height: 150px;
      background: var(--yu-linear-bg-color);
      position: relative;
      overflow: hidden;
      width: 100%;
      img {
        display: inline-block;
        position: absolute;
        width: 80px;
        height: auto;
        opacity: 0.2;
        &.img1 {
          top: 0;
          right: 0;
        }
        &.img2 {
          bottom: 0;
          left: 0;
        }
      }
    }
  }

  .user-info {
    position: absolute;
    top: 66px;
    left: 13px;
    width: calc(100% - 26px);
    z-index: 9;
    .card-body-wrapper {
      .avatar {
        width: 60px;
        height: 60px;
        overflow: hidden;
        border-radius: 50%;
        margin-right: 16px;
        box-shadow: var(--yu-border-shadow--light);
        img {
          width: 100%;
          height: 100%;
        }
      }
      .info {
        color: rgba(36, 45, 61, 1);
        font-size: 12px;
        line-height: 18px;
        padding-top: 10px;
        text-align: left;
        width: calc(100% - 60px - 16px);
        .user-name {
          margin-bottom: 4px;
          font-weight: 600;
        }
      }
    }
  }

  .body {
    padding: 0 13px;
    margin-top: 10px;
  }
  .user-info-card {
    display: block;
    width: 100%;
    padding: 0;
    margin-bottom: 8px;
  }
  .user-info-list {
    font-size: 15px;
  }
}
</style>